package com.sqfw.project.utils;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5加密工具类
 *
 * @author dengqianyong
 *
 */
public class MD5Utils {

    private static final int SIGN_LENGTH = 31;

    public static String encrypt(String text) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(text.getBytes());
            String sign = new BigInteger(1, md.digest()).toString(16);
            if(sign.length() == SIGN_LENGTH){
                sign = "0" + sign;
            }
            return sign;
        } catch (NoSuchAlgorithmException e) {
        }
        return "";

    }

    public static String encrypt16(String text) {
        String md5 = encrypt(text);
        return md5.substring(8, 24);
    }

    /**
     *
     * @param source
     * @return
     */
    public static String getMD5Str(String source) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            byte[] byteArray = messageDigest.digest(source.getBytes("UTF-8"));
            StringBuffer md5StrBuff = new StringBuffer();
            for (int i = 0; i < byteArray.length; i++) {
                if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
                    md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
                } else {
                    md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
                }
            }
            return md5StrBuff.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String encryptPassword(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md5=MessageDigest.getInstance("MD5");
//		password=password.toLowerCase();
        //加密后的字符串
        byte[] result =  md5.digest(password.getBytes("utf-8"));
        StringBuffer sb = new StringBuffer();
        for (int j = 0; j < result.length; ++j) {
            int b = result[j] & 0xFF;
            if (b < 0x10) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(b));
        }
        return sb.toString();
    }
    /**
     * md5加密，异常时返回空字符串
     * @param msg 加密字符串
     * @return
     */
    public static String md5(String msg){
        String s  = "";
        try {
            s = encryptPassword(msg);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return s;
    }
}

